package com.zdxlz.fcmp.business.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zdxlz.fcmp.business.entity.TaskEntity;
import com.zdxlz.fcmp.business.service.ITaskService;
import com.zdxlz.fcmp.common.core.constant.enums.MqttResCode;
import com.zdxlz.fcmp.common.core.util.JsonUtil;
import com.zdxlz.fcmp.common.mqtt.dto.IctMqttResponse;
import com.zdxlz.fcmp.common.mqtt.handler.MqttMessageRouter;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

/**
 * @author: aman
 * @date 2025/2/14 21:05
 * @description
 */

@Configuration
@AllArgsConstructor
@Slf4j
public class MqttHandlerConfiguration {

    private final MqttMessageRouter router;
    private final ITaskService taskService;

    @PostConstruct
    public void registerHandlers() {
        // 处理设备上报消息
        router.registerWildcardHandler("/gateway/plugin/report/#", (topic, payload) -> {
            String jsonString = new String(payload, StandardCharsets.UTF_8);
            IctMqttResponse<?> response = JsonUtil.fromJson(jsonString, IctMqttResponse.class);

            if (response.getCode() == MqttResCode.SUCESS.getCode()) {
                LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
                int lastSlashIndex = topic.lastIndexOf('/');
                wrapper.eq(TaskEntity::getMac,topic.substring(lastSlashIndex + 1));
                taskService.remove(wrapper);

                // TODO 更新状态
            }

            log.info("处理设备响应, topic: {}，响应数据：{}", topic, response);
            // 在这里可以完成 pendingResponses 中对应 future 的 complete 操作
            return CompletableFuture.completedFuture(null);
        });

        // 处理设备响应消息
        router.registerWildcardHandler("/gateway/plugin/reply/#", (topic, payload) -> {

            String jsonString = new String(payload, StandardCharsets.UTF_8);
            IctMqttResponse<?> response = JsonUtil.fromJson(jsonString, IctMqttResponse.class);

            if (response.getCode() == MqttResCode.SUCESS.getCode()) {
                LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
                int lastSlashIndex = topic.lastIndexOf('/');
                wrapper.eq(TaskEntity::getMac,topic.substring(lastSlashIndex + 1));
                taskService.remove(wrapper);
                // TODO 更新状态
            }else{
                TaskEntity task = new TaskEntity();
                // TODO 更新状态
            }

            log.info("处理设备响应, topic: {}，响应数据：{}", topic, response);
            // 在这里可以完成 pendingResponses 中对应 future 的 complete 操作
            return CompletableFuture.completedFuture(null);
        });

    }

}
